﻿using System;
using System.Collections;
using System.Windows.Forms;
using OFX.Aggregator.Infrastructure;

namespace OFX.Aggregator.Application
{
	public partial class OFXAggregatorMainForm : Form
	{
		private readonly IStatementProcessingWorkflow workflow;
		private readonly IStatementSourceRepository statementSourceRepository;

		public OFXAggregatorMainForm(IStatementSourceRepository statementSourceRepository, IStatementProcessingWorkflow workflow)
		{
			this.InitializeComponent();

			SingletonContainer.Resolve<IProgressReport>
				(new Hashtable {{"progressBar", this.progressBar}});

			this.statementSourceRepository = statementSourceRepository;
			this.workflow = workflow;
			this.workflow.WorkflowStarted += this.workflow_WorkflowStarted;
			this.workflow.WorkflowFinished += this.workflow_WorkflowFinished;
		}

		private void workflow_WorkflowStarted(object sender, EventArgs e)
		{
			Cursor = Cursors.WaitCursor;
		}

		private void workflow_WorkflowFinished(object sender, EventArgs e)
		{
			Cursor = Cursors.Default;
		}

		private void OFXAggregatorMainForm_Activated(object sender, EventArgs e)
		{
			// TODO: Replace this with a predicate
			/*var selectedPanelId = (string) this.comboBoxStatementSources.SelectedValue;
			foreach (StatementSource statementSource in this.comboBoxStatementSources.Items)
			{
				if (statementSource.PanelId == selectedPanelId)
				{
					if (statementSource.Retrieval.CanRetrieveStatement())
					{
						// No need to search for a enabled StatementSource
						return;
					}
				}
			}

			foreach (StatementSource statementSource in this.comboBoxStatementSources.Items)
			{
				if (statementSource.Retrieval.CanRetrieveStatement())
				{
					this.comboBoxStatementSources.SelectedValue = statementSource.PanelId;
					break;
				}
			}*/
		}

		private void buttonSetupNewAccount_Click(object sender, EventArgs e)
		{
			using (var form = SingletonContainer.Resolve<AccountSetupPage>())
			{
				if (form.ShowDialog(this) == DialogResult.OK)
				{
					statementSourceRepository.StatementSources.Add(form.ConfiguredStatementSource);
				}
			}
		}
	}
}